﻿/* MarcGrabanski.com */
/* Pop-Up Calendar Built from Scratch by Marc Grabanski */
//使用说明：var time = new Date().format("yyyy-MM-dd");
 Date.prototype.format = function(format) //author: meizz
    {
        var o = {
            "M+": this.getMonth() + 1, //month
            "d+": this.getDate(),    //day
            "h+": this.getHours(),   //hour
            "m+": this.getMinutes(), //minute
            "s+": this.getSeconds(), //second
            "q+": Math.floor((this.getMonth() + 3) / 3),  //quarter
            "S": this.getMilliseconds() //millisecond
        }
        if (/(y+)/.test(format)) format = format.replace(RegExp.$1,
            (this.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o) if (new RegExp("(" + k + ")").test(format))
            format = format.replace(RegExp.$1,
              RegExp.$1.length == 1 ? o[k] :
                ("00" + o[k]).substr(("" + o[k]).length));
        return format;
    }
var popUpCal = {
    selectedMonth: new Date().getMonth(), // 0-11
    selectedYear: new Date().getFullYear(), // 4-digit year
    selectedDay: new Date().getDate(),
    init: function() {
        $('<div id="calendarDiv" class="modalBackground"></div>').appendTo(".dateParent");
        var x = $('.calendarSelectDate');
        var y = $('#calendarDiv');
		var iDay,iNum=0;
		$("#tableAddress .jQaddRd").each(function(){
			if($(this).attr("checked")){
				iDay=parseInt($(this).attr("dates"));
				iNum+=1;
			}
		});
        if (x.val() == "") {
			var t=new Date();
			var iToDay=t.getDate();
			var iToMon=t.getMonth();
			var iToYear=t.getFullYear();
			if(iNum>0){var dCurDate=new Date(iToYear,iToMon,iToDay+iDay).format("yyyy-MM-dd");
			}else{
				//var dCurDate=new Date(iToYear,iToMon,iToDay).format("yyyy-MM-dd");
			}
            setVal = dCurDate;
            //x.find('input').val(setVal);
        }
        x.toggle(function() {
			$(this).removeClass("error");
			var iNum1=0;
			$("#tableAddress .jQaddRd").each(function(){
				if($(this).attr("checked")){
					iNum1+=1;
				}
			});
			
			popUpCal.input = $(this).find('input');
			y.hide();
			setPos(this, y); // setPos(targetObj,moveObj)
			setDateFromField();
			popUpCal.drawCalendar();
		
            // $("#county").hide();
        },function(){
			y.hide();
		});
    }, // end init function
    drawCalendar: function() {
        html = '';
        html += '<table cellpadding="0" cellspacing="0" id="linksTable"><tr>';
        html += ' <td><a id="prevYear" href="javascript:void(0);"></a></td>';
	html += ' <td><a id="prevMonth" href="javascript:void(0);"><<</a></td>';
        html += '<td class="calendarHeader">' + popUpCal.selectedYear + '年' + getMonthName(popUpCal.selectedMonth) + '</td>';
        html += ' <td><a id="nextMonth" href="javascript:void(0);">>></a></td>';
	html += ' <td><a id="nextYear" href="javascript:void(0);"></a></td>';
        //html += ' <tr><td><a id="prevYear"><< 上一年</a></td>';
        // html += ' <td><a id="nextYear">下一年 >></a></td>';
        html += '</tr></table>';
        html += '<table id="calendar" cellpadding="0" cellspacing="0"><tr>';
        //html += '<th colspan="7" class="calendarHeader">'+getMonthName(popUpCal.selectedMonth)+' '+popUpCal.selectedYear+'</th>';
        html += '</tr><tr class="weekDaysTitleRow">';
        var weekDays = new Array('日', '一', '二', '三', '四', '五', '六');
        for (var j = 0; j < weekDays.length; j++) {
            html += '<td width="10%">' + weekDays[j] + '</td>';
        }
        daysInMonth = getDaysInMonth(popUpCal.selectedYear, popUpCal.selectedMonth);
        startDay = getFirstDayofMonth(popUpCal.selectedYear, popUpCal.selectedMonth);
        numRows = 0;
        printDate = 1;
        if (startDay != 7) { numRows = Math.ceil(((startDay + 1) + (daysInMonth)) / 7); } // calculate the number of rows to generate
        // calculate number of days before calendar starts
        (startDay != 7) ? noPrintDays = startDay + 1 : noPrintDays = 1; // if monday print right away
        // function with cruft for figuring out what day to highlight
        selectedDate = popUpCal.input.val().split('/');
        if (selectedDate.length == 3) {
            thisMonth = parseFloat(selectedDate[0]) - 1;
            thisDay = parseFloat(selectedDate[1]);
            thisYear = parseFloat(selectedDate[2]);
        } else {
            thisDay = new Date().getDate();
            thisMonth = new Date().getMonth();
            thisYear = new Date().getFullYear();
        }
        // create calendar rows
        for (var e = 0; e < numRows; e++) {
            html += '<tr class="weekDaysRow">';
            // create calendar days
            for (var f = 0; f <= 6; f++) {
                if ((printDate == thisDay)
                        && (popUpCal.selectedYear == thisYear)
                        && (popUpCal.selectedMonth == thisMonth)
                        && (noPrintDays == 0)) {
                    html += '<td id="today" class="weekDaysCell">';

                } else {
					if(f == 0||f == 6) html += '<td class="weekDaysCell speCell">';
					else html += '<td class="weekDaysCell">';

                }
                if (noPrintDays == 0) {
                    if (printDate <= daysInMonth) html += '<a href="javascript:void(0);">' + printDate + '</a>';
					//else html += '&nbsp;';
                    printDate++;
                }
                html += '</td>';
                if (noPrintDays > 0) noPrintDays--;
            }
            html += '</tr>';
        }
       //html += '<td conspan="7" class="weekDaysCell"><a id="closeCalender" href="javascript:void(0);">关闭</a></td>';
        html += '</table>';


        // add calendar to element to calendar Div
        var calendarDiv = $('#calendarDiv');
        calendarDiv.empty().append(html).show("medium");
        popUpCal.setupLinks();
        /* close button link
        $('#closeCalender').click(function() {
            calendarDiv.hide();
        });*/
        // setup next and previous links
        $('#prevMonth').click(function() {
            popUpCal.selectedMonth--;
            if (popUpCal.selectedMonth < 0) {
                popUpCal.selectedMonth = 11;
                popUpCal.selectedYear--;
            }
            popUpCal.drawCalendar();
        });
        $('#nextMonth').click(function() {
            popUpCal.selectedMonth++;
            if (popUpCal.selectedMonth > 11) {
                popUpCal.selectedMonth = 0;
                popUpCal.selectedYear++;
            }
            popUpCal.drawCalendar();
        });
        $('#prevYear').click(function() {
            popUpCal.selectedYear--;
            popUpCal.drawCalendar();
        });
        $('#nextYear').click(function() {
            popUpCal.selectedYear++;
            popUpCal.drawCalendar();
        });
    }, // end drawCalendar function
    setupLinks: function() {
        // set up link events on calendar table
        var x = $('#calendar a');
		var iDay=0,iNum=0;
		$("#tableAddress .jQaddRd").each(function(){
			if($(this).attr("checked")){
				iDay=parseInt($(this).attr("dates"));
				iNum+=1;
			}
		});
		

        $(".weekDaysCell").mouseover(function() {
		   $(this).addClass("weekDaysCellOver");
        });
        $(".weekDaysCell").mouseout(function() {
           $(this).removeClass("weekDaysCellOver");
        });

        x.click(function() {
            /* $("#county").show();*/

			if($(this).html()!="关闭"){
				popUpCal.selectedDay = $(this).html();
				//var iSelDay=parseInt($(this).html());
				var t=new Date();
				var iToDay=t.getDate();
				var iToMon=t.getMonth();
				var iToYear=t.getFullYear();
				var dRigDay=new Date(iToYear,iToMon,(iToDay+iDay));

				var dSelDay=new Date(popUpCal.selectedYear,popUpCal.selectedMonth,popUpCal.selectedDay);//选择日期转成时间串
				
					var dMaxDay = new Date(iToYear,iToMon,(iToDay+iDay+30));


				//if(dSelDay>=dRigDay  && dSelDay <= dMaxDay ){
					$('#calendarDiv').hide();
					$('.error').hide();
					$(".jQaddBtn").show();
					//日期点击后把当前A的值赋给input

					if (popUpCal.selectedDay != '关闭') {
						setVal = formatDate(popUpCal.selectedDay, popUpCal.selectedMonth, popUpCal.selectedYear);
						popUpCal.input.val(setVal);
						//$('.calendarSelectDate').trigger("click");
					}
				//}
				//else{
					//var sErr="请选择"+iToday+"日后"+iDay+"天";
					//var sErr="请选择"+dRigDay.format("yyyy-MM-dd")+"至"+dMaxDay.format("yyyy-MM-dd")+"的日期！";
					//$('.error').hide();
					//$(".calendarSelectDate .error").remove();
					//$('<span class="error">' + sErr + '</span>').appendTo("div.calendarSelectDate");
				//}
			}
        });
    } // end setupLinks function
}
/* Functions Dealing with Dates */
function formatDate(Day, Month, Year) {
    Month++; // adjust javascript month
    if (Month < 10) Month = '0' + Month; // add a zero if less than 10
    if (Day < 10) Day = '0' + Day; // add a zero if less than 10
    var dateString = Year + '-' + Month + '-' + Day;
    return dateString;
}
function setDateFromField() {
    selectedDate = popUpCal.input.val().split('/');
    if (selectedDate.length == 3) {
        popUpCal.selectedMonth = parseFloat(selectedDate[0]) - 1;
        popUpCal.selectedDay = parseFloat(selectedDate[1]);
        popUpCal.selectedYear = parseFloat(selectedDate[2]);
    } else {
        popUpCal.selectedDay = new Date().getDate();
        popUpCal.selectedMonth = new Date().getMonth();
        popUpCal.selectedYear = new Date().getFullYear();
    }
}
function getMonthName(month) {
    var monthNames = new Array('1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月');
    return monthNames[month];
}
function getDayName(day) {
    var dayNames = ""; //new Array('星期一','星期二','星期三','星期四','星期五','星期六','星期日')
    return dayNames[day];
}
function getDaysInMonth(year, month) {
    return 32 - new Date(year, month, 32).getDate();
}
function getFirstDayofMonth(year, month) {
    var day;
    day = new Date(year, month, 0).getDay();
    return day;
}
/* Position Functions */
function setPos(targetObj, moveObj) {
	 var Sys = {};
        var ua = navigator.userAgent.toLowerCase();
        if (window.ActiveXObject)
            Sys.ie = ua.match(/msie ([\d.]+)/)[1]
        else if (document.getBoxObjectFor)
            Sys.firefox = ua.match(/firefox\/([\d.]+)/)[1]

    var coors = findPos(targetObj);
    moveObj.css('position', 'absolute');
    
    moveObj.css('top', 30 + 'px');
	if(navigator.appVersion.indexOf("MSIE 6.") != -1){//ie6
		coors[0]+=6;
	}
    moveObj.css('left', coors[0] - 420 + 'px');
}
function findPos(obj) {
    var curleft = curtop = 0;
    if (obj.offsetParent) {
        curleft = obj.offsetLeft
        curtop = obj.offsetTop
        while (obj = obj.offsetParent) {
            curleft += obj.offsetLeft
            curtop += obj.offsetTop
        }
    }
    return [curleft, curtop];
}

// Initialize the calendar
$(document).ready(function() {
    popUpCal.init();
});